package com.zhan.drugStore.util;

import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 版权：上海极和信息科技有限公司
 * 功能：工具类
 * 作者：朱伟峰
 * 邮箱：zhuweifeng24@gmail.com
 * 日期：2015年11月26日
 */
public class ToolUtils {
    private static final Logger logger = LoggerFactory.getLogger(ToolUtils.class);

    public static String genNull(String str) {
        return str == null ? "" : str;
    }

    public static boolean isEmpty(String str) {
        return (str == null) || (str.equals(""));
    }

    public static boolean isTrimEmpty(String str) {
        return (str == null) || (str.equals("")) || (isEmpty(str.trim()));
    }

    public static String genString(Object value) {
        if (value == null)
            return null;
        else if (value instanceof String)
            return (String) value;
        else
            return value.toString();
    }

    public static String genString(Object value, String defaultValue) {
        if (value == null)
            return defaultValue;
        else if (value instanceof String)
            return (String) value;
        else
            return value.toString();
    }

    public static int genInt(String sValue) {
        return ToolUtils.genInt(sValue, 0);
    }

    public static int genInt(String sValue, int defaultValue) {
        if (ToolUtils.isEmpty(sValue)) {
            return defaultValue;
        }

        try {
            return Integer.parseInt(sValue);
        } catch (Exception ex) {
            logger.error(String.format("parseInt exception String is %s", sValue), ex);

            return defaultValue;
        }
    }

    public static int genInt(Object value) {
        if (value == null)
            return 0;
        else if (value instanceof Integer)
            return (int) value;
        else
            return ToolUtils.genInt(value.toString());
    }

    public static long genLong(String sValue) {
        return ToolUtils.genLong(sValue, 0L);
    }

    public static long genLong(String sValue, long defaultValue) {
        if (ToolUtils.isEmpty(sValue)) {
            return defaultValue;
        }

        try {
            return Long.parseLong(sValue);
        } catch (Exception ex) {
            logger.error(String.format("parseLong exception String is %s", sValue), ex);

            return defaultValue;
        }
    }

    public static long genLong(Object value) {
        if (value == null)
            return 0L;
        else if (value instanceof Long)
            return (long) value;
        else
            return ToolUtils.genLong(value.toString());
    }

    public static short genShort(String sValue) {
        return ToolUtils.genShort(sValue, (short) 0);
    }

    public static short genShort(String sValue, short defaultValue) {
        if (ToolUtils.isEmpty(sValue)) {
            return defaultValue;
        }

        try {
            return Short.parseShort(sValue);
        } catch (Exception ex) {
            logger.error(String.format("parseShort exception String is %s", sValue), ex);

            return defaultValue;
        }
    }

    public static short genShort(Object value) {
        if (value == null)
            return 0;
        else if (value instanceof Short)
            return (short) value;
        else
            return ToolUtils.genShort(value.toString());
    }

    public static byte genByte(String sValue) {
        return ToolUtils.genByte(sValue, (byte) 0);
    }

    public static byte genByte(String sValue, byte defaultValue) {
        if (ToolUtils.isEmpty(sValue)) {
            return defaultValue;
        }

        try {
            return Byte.parseByte(sValue);
        } catch (Exception ex) {
            logger.error(String.format("parseByte exception String is %s", sValue), ex);

            return defaultValue;
        }
    }

    public static byte genByte(Object value) {
        if (value == null)
            return (byte) 0;
        else if (value instanceof Byte)
            return (byte) value;
        else
            return ToolUtils.genByte(value.toString());
    }

    public static float genFloat(String sValue) {
        return ToolUtils.genFloat(sValue, 0.0f);
    }

    public static float genFloat(String sValue, float defaultValue) {
        if (ToolUtils.isEmpty(sValue)) {
            return defaultValue;
        }

        try {
            return Float.parseFloat(sValue);
        } catch (Exception ex) {
            logger.error(String.format("parseFloat exception String is %s", sValue), ex);

            return defaultValue;
        }
    }

    public static float genFloat(Object value) {
        if (value == null)
            return 0F;
        else if (value instanceof Float)
            return (float) value;
        else
            return ToolUtils.genFloat(value.toString());
    }

    public static double genDouble(String sValue) {
        return ToolUtils.genDouble(sValue, 0.0D);
    }

    public static double genDouble(String sValue, double defaultValue) {
        if (ToolUtils.isEmpty(sValue)) {
            return defaultValue;
        }

        try {
            return Double.parseDouble(sValue);
        } catch (Exception ex) {
            logger.error(String.format("parseDouble exception String is %s", sValue), ex);

            return defaultValue;
        }
    }

    public static double genDouble(Object value) {
        if (value == null)
            return 0D;
        else if (value instanceof Double)
            return (double) value;
        else
            return ToolUtils.genDouble(value.toString());
    }

    public static Date genDate(String sValue, String sFormat) {
        Date dValue;
        try {
            if ((sFormat == null) || (sFormat.trim().equals(""))) {
                sFormat = "yyyy-MM-dd HH:mm:ss";
            }
            SimpleDateFormat dateFormat = new SimpleDateFormat(sFormat);

            dValue = dateFormat.parse(sValue);
        } catch (Exception ex) {
            dValue = new Date(0L);
            logger.error("exception is ....", ex);
        }

        return dValue;
    }

    public static Date genDate(String sValue) {
        return genDate(sValue, "");
    }

    public static Date genJustDate(String sValue) {
        return genDate(sValue, "yyyy-MM-dd");
    }

    public static Date genDate(long lValue, String sFormat) {
        if ((sFormat == null) || (sFormat.trim().equals(""))) {
            sFormat = "yyyy-MM-dd HH:mm:ss";
        }
        return genDate(formatDate(new Date(lValue), sFormat), sFormat);
    }

    public static long genLong(Date date) {
        if (date != null) {
            return date.getTime();
        }
        return 0L;
    }

    public static Date genDate(long value) {
        if (value != 0L) {
            return genDate(value, "");
        }
        return null;
    }

    public static Date genJustDate(long lValue) {
        return genDate(lValue, "yyyy-MM-dd");
    }

    public static double formatData(double fData, String sFormatString) {
        try {
            DecimalFormat df = new DecimalFormat(sFormatString);

            return Double.parseDouble(df.format(fData));
        } catch (NumberFormatException nfe) {
            System.out.println("fData========" + fData);
        }
        return 0.0D;
    }

    public static String formatDate(long lDate, String sFormat) {
        return formatDate(new Date(lDate), sFormat);
    }

    public static String formatDate(long lDate) {
        return formatDate(new Date(lDate), "");
    }

    public static String formatTimes(long lDate, String level) {
        String dateStr = "";
        int days = 0;
        int hours = 0;
        int minutes = 0;
        long timesHour = 0L;
        long timesMinute = 0L;
        long currentTime = new Date().getTime();
        if (currentTime >= lDate) {
            long times = currentTime - lDate;
            days = (int) (times / 86400000L);
            timesHour = times % 86400000L;
            hours = (int) (timesHour / 3600000L);
            timesMinute = timesHour % 3600000L;
            minutes = (int) (timesMinute / 60000L);
            if ("".equals(level)) {
                if ((days == 0) && (hours == 0) && (minutes == 0)) {
                    dateStr = "刚刚";
                } else if ((days != 0) && (hours == 0) && (minutes == 0)) {
                    dateStr = String.valueOf(days) + "天前";
                } else if ((days == 0) && (hours != 0) && (minutes == 0)) {
                    dateStr = String.valueOf(hours) + "小时前";
                } else if ((days == 0) && (hours == 0) && (minutes != 0)) {
                    dateStr = String.valueOf(minutes) + "分钟前";
                } else if ((days != 0) && (hours == 0) && (minutes != 0)) {
                    dateStr = String.valueOf(days) + "天前";
                } else if ((days != 0) && (hours != 0) && (minutes == 0)) {
                    dateStr = String.valueOf(days) + "天"
                            + String.valueOf(hours) + "小时前";
                } else if ((days == 0) && (hours != 0) && (minutes != 0)) {
                    dateStr = String.valueOf(hours) + "小时"
                            + String.valueOf(minutes) + "分钟前";
                } else {
                    dateStr = String.valueOf(days) + "天"
                            + String.valueOf(hours) + "小时前";
                }
            } else if ("1".equals(level))
                if ((days == 0) && (hours == 0) && (minutes == 0)) {
                    dateStr = "刚刚";
                } else if ((days != 0) && (hours == 0) && (minutes == 0)) {
                    dateStr = String.valueOf(days) + "天前";
                } else if ((days == 0) && (hours != 0) && (minutes == 0)) {
                    dateStr = String.valueOf(hours) + "小时前";
                } else if ((days == 0) && (hours == 0) && (minutes != 0)) {
                    dateStr = String.valueOf(minutes) + "分钟前";
                } else if ((days != 0) && (hours == 0) && (minutes != 0)) {
                    dateStr = String.valueOf(days) + "天前";
                } else if ((days != 0) && (hours != 0) && (minutes == 0)) {
                    dateStr = String.valueOf(days) + "天前";
                } else if ((days == 0) && (hours != 0) && (minutes != 0)) {
                    dateStr = String.valueOf(hours) + "小时前";
                } else dateStr = String.valueOf(days) + "天前";
        } else {
            dateStr = "刚刚";
        }

        return dateStr;
    }

    public String formatTimes(Date date) {
        long lDate = date.getTime();
        return formatTimes(lDate, "");
    }

    public static String formatJustDate(long lDate) {
        return formatDate(new Date(lDate), "yyyy-MM-dd");
    }

    public static String formatDate(Date date, String sFormat) {
        if (date == null)
            return "";

        if ((sFormat == null) || (sFormat.trim().equals(""))) {
            sFormat = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat df = new SimpleDateFormat(sFormat);

        return df.format(date);
    }

    public static String ajaxEncode(String str, String encode) {
        String encodeStr = "";
        try {
            encodeStr = java.net.URLDecoder.decode(str, encode);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }

    /**
     * 给指定日期增加天数
     *
     * @param strDate 指定日期 yyyy-MM-dd格式
     * @param day     增加天数
     * @return 增加天数后的日期 yyyy-MM-dd格式
     */
    public static String addDate(String strDate, int day) {
        if (isEmpty(strDate) || day == 0)
            return "";

        String sFormat = "yyyy-MM-dd";

        try {
            SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat(sFormat);
            Date dateYMD = localSimpleDateFormat.parse(strDate);
            SimpleDateFormat format = new SimpleDateFormat(sFormat);

            // 增加天数
            Calendar ca = Calendar.getInstance();
            ca.setTime(dateYMD);
            ca.add(Calendar.DATE, day);
            dateYMD = ca.getTime();

            String backTime = format.format(dateYMD);
            return backTime;
        } catch (Exception e) {
            logger.error("strDate：" + strDate + " day：" + day);
        }
        return "";
    }


    /**
     * 给日期增加天数,格式为yyyy年MM月dd日 HH时mm分ss秒
     *
     * @param strDate
     * @param day
     * @return
     */
    public static String addDate(String strDate, long day) {
        if (isEmpty(strDate) || day == 0)
            return "";

        String sFormat = "yyyy年MM月dd日 HH时mm分ss秒";

        try {
            SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat(sFormat);
            Date dateYMD = localSimpleDateFormat.parse(strDate);
            SimpleDateFormat format = new SimpleDateFormat(sFormat);

            // 增加天数
            Calendar ca = Calendar.getInstance();
            ca.setTime(dateYMD);
            ca.add(Calendar.DATE, (int) day);
            dateYMD = ca.getTime();

            String backTime = format.format(dateYMD);
            return backTime;
        } catch (Exception e) {
            logger.error("strDate：" + strDate + " day：" + day);
        }
        return "";
    }

    public static Date addDate(Date date, int day) {
        try {
            // 增加天数
            Calendar ca = Calendar.getInstance();
            ca.setTime(date);
            ca.add(Calendar.DATE, day);

            return ca.getTime();
        } catch (Exception e) {
            logger.error("date：" + date + " day：" + day);
        }
        return null;
    }

    /**
     * <p>Description:判断list是否为空</p>
     *
     * @param list
     * @return
     * @date 2016年4月25日 下午3:17:10
     */
    public static <T> boolean isEmpty(List<T> list) {
        if (list == null || list.size() == 0)
            return true;
        return false;
    }

    /**
     * 对字符串md5加密
     *
     * @param str
     * @return
     */
    public static String genMD5(String str) {
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes());
            // digest()最后确定返回md5 hash值，返回值为8为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            return new BigInteger(1, md.digest()).toString(16);
        } catch (Exception e) {
            logger.error("MD5加密出现错误：" + str);
            return "";
        }
    }

    /**
     * 对密码加密 md5
     *
     * @param source         要加密的明文
     * @param salt           盐
     * @param hashIterations 散列次数
     * @return
     */
    public static String genMD5(String source, Object salt, Integer hashIterations) {
        return new Md5Hash(source, salt, hashIterations).toString();
    }

    /**
     * 生成UUID
     *
     * @return
     */
    public static String genUUID() {
        String uuid = UUID.randomUUID().toString().toUpperCase().replaceAll("-", "");
        return uuid;
    }

    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * <p>
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值，究竟哪个才是真正的用户端的真实IP呢？
     * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
     * <p>
     * 如：X-Forwarded-For：192.168.1.110, 192.168.1.120, 192.168.1.130,
     * 192.168.1.100
     * <p>
     * 用户真实IP为： 192.168.1.110
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ToolUtils.isTrimEmpty(ip) || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("Proxy-Client-IP");
        if (ToolUtils.isTrimEmpty(ip) || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("WL-Proxy-Client-IP");
        if (ToolUtils.isTrimEmpty(ip) || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("HTTP_CLIENT_IP");
        if (ToolUtils.isTrimEmpty(ip) || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        if (ToolUtils.isTrimEmpty(ip) || "unknown".equalsIgnoreCase(ip))
            ip = request.getRemoteAddr();
        return ip;
    }

    /**
     * 根据键值获取数据
     *
     * @param data 数据map
     * @param key  键值
     * @return
     */
    public static String getStringFromMap(Map<String, Object> data, String key) {
        String result = "";
        if (data == null || data.isEmpty() || !data.containsKey(key))
            return result;

        result = data.get(key).toString();
        return result;
    }

    /**
     * 根据键值获取数据
     *
     * @param data 数据map
     * @param key  键值
     * @return
     */
    public static int getIntFromMap(Map<String, Object> data, String key) {
        String result = getStringFromMap(data, key);
        if (!isEmpty(result))
            return genInt(result);
        else
            return 0;
    }

    /**
     * 根据键值获取数据
     *
     * @param data 数据map
     * @param key  键值
     * @return
     */
    public static long getLongFromMap(Map<String, Object> data, String key) {
        String result = getStringFromMap(data, key);
        if (!isEmpty(result))
            return genLong(result);
        else
            return 0l;
    }

    /**
     * 根据键值获取数据
     *
     * @param data 数据map
     * @param key  键值
     * @return
     */
    public static double getDoubleFromMap(Map<String, Object> data, String key) {
        String result = getStringFromMap(data, key);
        if (!isEmpty(result))
            return genDouble(result);
        else
            return 0d;
    }

    private static final String charStr = "0123456789";

    /**
     * 生成随机码
     *
     * @param length 需要生成几位
     * @return 生成的随机码
     */
    public static String genRandomCode(int length) {
        String result = "";
        for (int i = 0; i < length; i++) {
            result += charStr.charAt((int) (Math.random() * charStr.length()));
        }

        return result;
    }

    /**
     * 拿到分页的总页数
     *
     * @param totalNum 总记录数
     * @param pageSize 每页几条数据
     * @return 拿到分页的总页数 add by zhuweifeng update at 2012-03-22
     */
    public static int totalPage(int totalNum, int pageSize) {
        int pageCount = 0;
        if (totalNum == 0 || pageSize == 0)
            return pageCount;
        if (totalNum <= 0 || pageSize <= 0)
            return pageCount;

        if ((totalNum % pageSize) == 0)
            pageCount = (totalNum / pageSize);
        else
            pageCount = (totalNum / pageSize) + 1;
        return pageCount;
    }

    /**
     * 随机指定范围内N个不重复的数
     * 最简单最基本的方法
     *
     * @param min 指定范围最小值
     * @param max 指定范围最大值
     * @param n   随机数个数
     */
    public static int[] randomArray(int min, int max, int n) {
        int len = max - min + 1;
        if (max < min || n > len) {
            return null;
        }

        // 初始化给定范围的待选数组
        int[] source = new int[len];
        for (int i = min; i < min + len; i++) {
            source[i - min] = i;
        }

        int[] result = new int[n];
        Random rd = new Random();
        int index = 0;
        for (int i = 0; i < result.length; i++) {
            // 待选数组0到(len-2)随机一个下标
            index = Math.abs(rd.nextInt() % len--);
            // 将随机到的数放入结果集
            result[i] = source[index];
            // 将待选数组中被随机到的数，用待选数组(len-1)下标对应的数替换
            source[index] = source[len];
        }
        return result;
    }

    // 将数字转成中文数字
    public static String int2chineseNum(int src) {
        final String num[] = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
        final String unit[] = {"", "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千"};
        String dst = "";
        int count = 0;
        while (src > 0) {
            dst = (num[src % 10] + unit[count]) + dst;
            src = src / 10;
            count++;
        }
        return dst.replaceAll("零[千百十]", "零").replaceAll("零+万", "万").replaceAll("零+亿", "亿").replaceAll("亿万", "亿零").replaceAll("零+", "零").replaceAll("零$", "");
    }

    /**
     * 格式化数量<br/>
     * 保留4位小数
     *
     * @param amount
     * @return
     */
    public static double formatAmount(double amount) {
        return formatData(amount, "0.0000", 0.0D);
    }

    public static double formatData(double fData, String sFormatString, double rate) {
        if (ToolUtils.isTrimEmpty(sFormatString)) {
            sFormatString = "0.0000";
        }

        try {
            DecimalFormat df = new DecimalFormat(sFormatString);

            return Double.parseDouble(df.format(fData + rate));
        } catch (NumberFormatException nfe) {
            logger.error("fData========" + fData, nfe);
        }
        return 0.0D;
    }

    /**
     * 驼峰转 下划线
     * userName  ---->  user_name
     * user_name  ---->  user_name
     *
     * @param camelCaseStr 驼峰字符串
     * @return 带下滑线的String
     */
    public static String toUnderlineCase(String camelCaseStr) {
        if (camelCaseStr == null) {
            return null;
        }
        // 将驼峰字符串转换成数组
        char[] charArray = camelCaseStr.toCharArray();
        StringBuffer buffer = new StringBuffer();
        //处理字符串
        for (int i = 0, l = charArray.length; i < l; i++) {
            if (charArray[i] >= 65 && charArray[i] <= 90) {
                buffer.append("_").append(charArray[i] += 32);
            } else {
                buffer.append(charArray[i]);
            }
        }
        return buffer.toString();
    }

    /**
     * 转日期
     * 2021年05月17日 14时55分21秒 ---->  2021-05-17 14:55:21
     *
     * @param sValue
     * @return java.util.Date
     **/
    public static Date toDate(String sValue) {
        return genDate(sValue, "yyyy年MM月dd日 HH时mm分ss秒");
    }

    /**
     * 字符串数组转int数组
     *
     * @param strArray
     * @return java.lang.Integer[]
     **/
    public static Integer[] getIntArrayFromStringArray(String[] strArray) {
        if (strArray == null) {
            return new Integer[0];
        }
        Integer[] result = new Integer[strArray.length];
        for (int i = 0; i < result.length; i++) {
            result[i] = Integer.parseInt(strArray[i]);
        }
        return result;
    }

    /**
     * 求并集
     *
     * @param m
     * @param n
     * @return
     */
    public static Integer[] union(Integer[] m, Integer[] n) {
        // 将数组转换为set集合
        Set<Integer> set1 = new HashSet<Integer>(Arrays.asList(m));
        Set<Integer> set2 = new HashSet<Integer>(Arrays.asList(n));

        // 合并两个集合
        set1.addAll(set2);

        Integer[] arr = {};
        return set1.toArray(arr);
    }

    /**
     * 求交集
     *
     * @param m
     * @param n
     * @return
     */
    public static Integer[] intersection(Integer[] m, Integer[] n) {
        List<Integer> rs = new ArrayList<Integer>();

        // 将较长的数组转换为set
        Set<Integer> set = new HashSet<Integer>(Arrays.asList(m.length > n.length ? m : n));

        // 遍历较短的数组，实现最少循环
        for (Integer i : m.length > n.length ? n : m) {
            if (set.contains(i)) {
                rs.add(i);
            }
        }

        Integer[] arr = {};
        return rs.toArray(arr);
    }

    /**
     * 求差集
     *
     * @param m
     * @param n
     * @return
     */
    public static Integer[] differenceSet(Integer[] m, Integer[] n) {
        // 将较长的数组转换为set
        Set<Integer> set = new HashSet<Integer>(Arrays.asList(m.length > n.length ? m : n));

        // 遍历较短的数组，实现最少循环
        for (Integer i : m.length > n.length ? n : m) {
            // 如果集合里有相同的就删掉，如果没有就将值添加到集合
            if (set.contains(i)) {
                set.remove(i);
            } else {
                set.add(i);
            }
        }

        Integer[] arr = {};
        return set.toArray(arr);
    }

    /**
     * 第一个数组 去除 第二个数组中的数据
     *
     * @param m
     * @param n
     * @return
     */
    public static Integer[] minusSet(Integer[] m, Integer[] n) {
        // 将较长的数组转换为set
        Set<Integer> set = new HashSet<Integer>(Arrays.asList(m));

        // 遍历较短的数组，实现最少循环
        for (Integer i : n) {
            //有相同的就删掉
            set.remove(i);
        }

        Integer[] arr = {};
        return set.toArray(arr);
    }

    /**
     * 去除Integer数组中的空值
     *
     * @param integers
     * @return Integer数组
     */
    public static Integer[] deleteArrayNull(Integer integers[]) {
        Integer integer[] = integers;

        // step1: 定义一个list列表，并循环赋值
        ArrayList<Integer> intList = new ArrayList<Integer>();
        for (int i = 0; i < integer.length; i++) {
            intList.add(integer[i]);
        }

        // step2: 删除list列表中所有的空值
        while (intList.remove(null)) ;
        while (intList.remove("")) ;

        // step3: 把list列表转换给一个新定义的中间数组，并赋值给它
        Integer intArrLast[] = intList.toArray(new Integer[intList.size()]);

        return intArrLast;
    }

    /**
     * 计算两数和差积商（无误差）
     *
     * @param a        数字a
     * @param b        数字b
     * @param operator 符号
     * @return 得数
     * @throws Exception 符号输入错误
     */
    public static double doubleCal(double a, double b, char operator) throws Exception {
        //默认除法运算精度
        final int DEF_DIV_SCALE = 10;
        BigDecimal b1 = BigDecimal.valueOf(a);
        BigDecimal b2 = BigDecimal.valueOf(b);
        switch (operator) {
            case '+':
                return b1.add(b2).doubleValue();
            case '-':
                return b1.subtract(b2).doubleValue();
            case '*':
                return b1.multiply(b2).doubleValue();
            case '/':
                //保留2位，ROUND_HALF_DOWN-向最接近数字方向舍入，如果与两个相邻数字的距离相等，则向下舍入。
                return b1.divide(b2, DEF_DIV_SCALE, BigDecimal.ROUND_HALF_DOWN).doubleValue();
            default:
                break;
        }
        throw new Exception("符号输入错误");
    }

    /**
     * 格式化时间
     *
     * @param date    日期时间
     * @param sFormat 格式
     * @return
     */
    public static String formatTime(Date date, String sFormat) {
        if (date == null)
            return "";

        if ((sFormat == null) || (sFormat.trim().equals(""))) {
            sFormat = "HH:mm:ss";
        }
        SimpleDateFormat df = new SimpleDateFormat(sFormat);

        return df.format(date);
    }

    /**
     * 判断字符串是否包含中文
     *
     * @param str
     * @return
     */
    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
     * 给指定日期 减去分钟
     *
     * @param strDate 指定日期 yyyy-MM-dd HH:mm:ss 格式
     * @param minute  减去分钟
     * @return 增加天数后的日期 yyyy-MM-dd HH:mm:ss 格式
     */
    public static String addDateTime(String strDate, int minute) {
        if (isEmpty(strDate) || minute == 0)
            return "";

        String sFormat = "yyyy-MM-dd HH:mm:ss";

        try {
            SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat(sFormat);
            Date dateYMD = localSimpleDateFormat.parse(strDate);
            SimpleDateFormat format = new SimpleDateFormat(sFormat);

            // 增加天数
            Calendar ca = Calendar.getInstance();
            ca.setTime(dateYMD);
            ca.add(Calendar.MINUTE, minute);
            dateYMD = ca.getTime();

            String backTime = format.format(dateYMD);
            return backTime;
        } catch (Exception e) {
            logger.error("strDate：" + strDate + " minute：" + minute);
        }
        return "";
    }

    /**
     * 给指定日期 减去秒
     *
     * @param strDate 指定日期 yyyy-MM-dd HH:mm:ss 格式
     * @param second  减去分钟
     * @return 增加天数后的日期 yyyy-MM-dd HH:mm:ss 格式
     */
    public static String addTime(String strDate, int second) {
        if (isEmpty(strDate) || second == 0)
            return "";

        String sFormat = "yyyy-MM-dd HH:mm:ss";

        try {
            SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat(sFormat);
            Date dateYMD = localSimpleDateFormat.parse(strDate);
            SimpleDateFormat format = new SimpleDateFormat(sFormat);

            // 增加天数
            Calendar ca = Calendar.getInstance();
            ca.setTime(dateYMD);
            ca.add(Calendar.SECOND, second);
            dateYMD = ca.getTime();

            String backTime = format.format(dateYMD);
            return backTime;
        } catch (Exception e) {
            logger.error("strDate：" + strDate + " second：" + second);
        }
        return "";
    }

    public static Boolean judgeBigDecimal(String value, Integer integer, Integer fraction) {
        boolean flag = false;
        try {
            if (value != null) {
                String regexp = "^[+-]?([0-9]{1,";
                regexp = regexp + integer + "}(\\.[0-9]{1,";
                regexp = regexp + fraction + "})?)$";
                // 判断是否是整数或者是携带一位到n位的小数
                Pattern pattern = Pattern.compile(regexp);
                if (pattern.matcher(value).matches()) {
                    flag = true;
                }
            }
        } catch (Exception e) {
            e.getMessage();
        }
        return flag;
    }

}
